package com.kfm.base.thread.day02;

public class Demo {
    public static void main(String[] args) {
        // 任务
        SellTicket sellTicket = new SellTicket();

        Thread t1 = new Thread(sellTicket, "一号窗口");
        Thread t2 = new Thread(sellTicket, "二号窗口");
        Thread t3 = new Thread(sellTicket, "三号窗口");

        t1.start();
        t2.start();
        t3.start();
    }
}


class SellTicket implements Runnable {

    // 总票数
    private int tickets = 100;

    private Object obj = new Object(); // 锁

    @Override
    public void run() {
        // 每一个任务都是一个售票的窗口
        while (true){ // 售票窗口一直开放
            synchronized (obj){ // 同步
                // 当票没卖完时，可以买票
                if (tickets > 0){
                    try {
                        // 模拟付钱和出票过程
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    // 购票成功
                    System.out.println(Thread.currentThread().getName() + " 售出第 【" + tickets -- + "】 张票");
                }
            }
        }
    }
}
